package com.johnson.news.fragment;


import android.content.Intent;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.johnson.news.BR;
import com.johnson.news.R;
import com.johnson.news.activity.NewsDetailActivity;
import com.johnson.news.model.bean.NewsItem;
import com.johnson.news.model.remote.RemoteDataSource;
import com.johnson.news.util.Utils;
import com.youmbe.library.BaseRecyclerAdapter;
import com.youmbe.library.util.MyToast;
import com.youmbe.library.view.BannerView;
import com.youmbe.library.view.MyProgressDialog;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link NewsListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NewsListFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private int catId;
    private String mId;


    public NewsListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param catId Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NewsListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static NewsListFragment newInstance(int catId, String param2) {
        NewsListFragment fragment = new NewsListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, catId);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            catId = getArguments().getInt(ARG_PARAM1);
            mId = getArguments().getString(ARG_PARAM2);
        }
    }

    View rootView;
    XRecyclerView news_list;
    BaseRecyclerAdapter<NewsItem> newsAdapter;
    BannerView loop_page;

    View loopPageView;
    TextView news_title;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if(rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_news_list, container, false);
            init();
        }
        return rootView;
    }
    boolean isFirstLoad = true;
    @Override
    public void onResume() {
        super.onResume();
        if (isFirstLoad){
            isFirstLoad = !isFirstLoad;
            pageIndex = 0;
            getData(true);
        }
    }

    boolean hasAddHeader = false;
    void init() {
        news_list = rootView.findViewById(R.id.news_list);

//        loop_page = rootView.findViewById(R.id.loop_page);
        if(catId == 0) {
            loopPageView = LayoutInflater.from(getActivity()).inflate(R.layout.view_topic_news, null, false);
            loop_page = loopPageView.findViewById(R.id.news_thumb);//new BannerView(getActivity());
            news_title = loopPageView.findViewById(R.id.news_title);
            ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Utils.screenWidth * 25 / 48);
            loopPageView.setLayoutParams(layoutParams);

            loop_page.setScreenRatio(48f / 25);
            loop_page.setLoopInterval(5);
            loop_page.setLayoutParams(layoutParams);
            loop_page.setOnPageClickListener(new BannerView.PageClickListener() {
                @Override
                public void pageclicklistener(int index) {
                    Object data = loop_page.getList().get(index);
                    if (data != null && data instanceof NewsItem) {
                        NewsItem newsItem = (NewsItem) data;
                        openNews(newsItem);
                    }
                }
            });

            loop_page.setOnPageChangeListener(new BannerView.PageChangeListener() {
                @Override
                public void pageChangeListener(int i) {
                    news_title.setText(topicNews.get(i).getTitle());
                }
            });

//            news_list.addHeaderView(loop_page);
//            hasAddHeader = true;
        }
//        else
//            loop_page.setVisibility(View.GONE);

        newsAdapter = new BaseRecyclerAdapter<>(getActivity(), R.layout.adapter_news, BR.data);
        news_list.setAdapter(newsAdapter);
        news_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        newsAdapter.setBindingViewClickListener(BR.onClickListener, onClickListener);

        news_list.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                if(catId == 0)
                    getTopicNews();
                getData(true);
            }

            @Override
            public void onLoadMore() {
                pageIndex++;
                getData(false);
            }
        });

        if(catId == 0) {
            getTopicNews();
        }
    }

    public void refreshData() {
        if(news_list != null && !isLoading) {
            news_list.scrollToPosition(0);
            news_list.refresh();
        }
    }

    boolean isLoading = false;
    int pageIndex;
    void getData(final boolean refresh) {
        if(isLoading)
            return;
        isLoading = true;

        if(refresh)
            pageIndex = 0;
        RemoteDataSource.getRemoteDataSource()
                .getNewsList(getActivity(), TextUtils.isEmpty(mId) ? Utils.MID : mId, catId, 0, catId == 0 ? 100 : Utils.PAGE_SIZE, pageIndex)
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        news_list.loadMoreComplete();
                        news_list.refreshComplete();
                        isLoading = false;
                    }
                })
                .subscribe(new Consumer<ArrayList<NewsItem>>() {
                    @Override
                    public void accept(ArrayList<NewsItem> newsItems) throws Exception {
                        pageIndex++;
                        if(refresh) {
                            newsAdapter.setData(newsItems);
                        } else {
                            newsAdapter.addData(newsItems);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MyToast.showToast(getString(R.string.loading_failed_txt), getActivity());
                    }
                });
    }

    ArrayList<NewsItem> topicNews = new ArrayList<>();
    void getTopicNews() {
        RemoteDataSource.getRemoteDataSource()
                .getTopicNews(getActivity(), TextUtils.isEmpty(mId) ? Utils.MID : mId, 10, 1)
                .subscribe(new Consumer<ArrayList<NewsItem>>() {
                    @Override
                    public void accept(ArrayList<NewsItem> newsItems) throws Exception {
//                        if(newsItems == null || newsItems.size() == 0) {
//                            if(hasAddHeader) {
//                                news_list.removeView(loop_page);
//                                newsAdapter.notifyDataSetChanged();
//                                hasAddHeader = false;
//                            }
////                            loop_page.setVisibility(View.GONE);
//                        } else {
//                            if(!hasAddHeader) {
//                                news_list.addHeaderView(loop_page);
//                                hasAddHeader = true;
//                            }
////                            loop_page.setVisibility(View.VISIBLE);
//                            loop_page.loadData(newsItems, "thumb");
//                        }
                        topicNews.clear();
                        if(newsItems != null && newsItems.size() > 0) {
                            topicNews.addAll(newsItems);
                            if(!hasAddHeader) {
                                news_list.addHeaderView(loopPageView);
                                hasAddHeader = true;
                            }
                            loop_page.loadData(newsItems, "thumb");
                        }
                    }
                });
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.news_layout:
                    Object object = view.getTag(R.id.adapter_tag_data);
                    if(object != null && object instanceof NewsItem) {
                        NewsItem newsItem = (NewsItem) object;
                        openNews(newsItem);
                    }
                    break;
            }
        }
    };

    void openNews(NewsItem newsItem) {
        Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("data", newsItem);
        intent.putExtras(bundle);
        startActivity(intent);
    }

}
